package ru.fadeev.crammer;


/**
 * PHBGetter class is a process that gets phrases containg custom words from
 * remote server called PhrasesBank (phrases are for use in Gaps Filling test)
 * When new phrases needed for some word, the phbTask created and stored in 
 * GFIndicesStorage. PHBGetter is a background process that gets phrases bank tasks
 * tasks from GFIndicesStorage, gets phrases from phrases bank and stores them into
 * the PhrasesCorpus (local corpus).
 * @author Konstantin Fadeyev
 *
 */
public class PHBGetter extends Thread {
	private GFIndicesStorage storage;
	private volatile boolean interrupted;
	
	
	/**
	 * Creates instance of PHBGetter
	 * @param storage object of GFIndicesStorage
	 */
	public PHBGetter(GFIndicesStorage storage) {
		this.storage = storage;
		interrupted = false;
	}
	
	/**
	 * Processes phrases banks tasks while not interrupted. Process can return
	 * on interruption while waiting for next task or waiting for response.
	 */
	public void run() {
		storage.loadPHBTasks();
		while(!interrupted) {
			storage.processPHBTask();
		}
	}
    
    
	/**
	 * Overwritten so volatile variable that is used to stop process is initialized.
	 */
    public void start() {
        interrupted = false;
        super.start();
    }
	
	/**
	 * Stops process. Function waits till it stops.
	 */
	public void stopGetter() {		
		interrupted = true;
		interrupt();
		try {
			this.join();
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(storage.getPHBTasksSize() != 0) {		
			storage.savePHBTasks();			
		}
	}
}
